package antoine.ear.exo.recoaccords;

import java.util.Iterator;
import java.util.Random;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.Sequence;
import javax.sound.midi.Track;

import antoine.ear.GUI;
import antoine.ear.exo.Exo;
import antoine.ear.generator.ChordGenerator;
import antoine.ear.generator.NoteGenerator;
import antoine.ear.generator.SequenceGenerator;
import antoine.ear.generator.chords.Dom7Generator;
import antoine.ear.generator.chords.Maj7Generator;
import antoine.ear.generator.chords.Min7Generator;

public class RecoChords  extends Exo {
	
	public int nbChords = 2;
	
	public RecoChords(int tempo, int octave, int aNbChords) {
		super(tempo, octave);
		this.nbChords = aNbChords;
		try {
			this.generate();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String getPrintableResult() {
		return soluce;
	}

	public void generate() throws Exception {
		try {
			GUI gui = GUI.getInstance();
			Sequence seq = new Sequence(Sequence.PPQ, 1);
			Track track = seq.createTrack();
						
			Random random = new Random();

			int note = 36+random.nextInt(12);
			indication = NoteGenerator.getNoteName(note);

			for (int i=0;i<nbChords;i++){
				
				track.add(createNoteOnEvent(note, 0+i*3));
				track.add(createNoteOffEvent(note, 3+i*3));
				track.add(createMetaMessOnEvent(note, 0+i*3, ACTIVATENOTE));
	            track.add(createMetaMessOnEvent(note, 3+i*3, DESACTIVATENOTE));
	            
				int ind = random.nextInt(gui.selectedChords.size());
				ChordGenerator gene = (ChordGenerator)gui.selectedChords.toArray()[ind];
				
				Iterator ite = gene.generate(note%12, 0+i*3, 3).iterator();
				while (ite.hasNext()){
					track.add((MidiEvent) ite.next());
				}
				
				this.soluce += gene.chordName()+ " | ";
				note = 36+random.nextInt(12);
			}
						
			this.setSequence(seq);
			setTempo(tempo);
		} catch (InvalidMidiDataException e) {
			throw new Exception(e); 
		}
	}

	public String getIndication() {
		return "La basse est " + indication;
	}
}
